package io.jee.medusa.firewall;

import javax.annotation.Resource;

import org.hibernate.LockMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.jee.medusa.orm.condition.Operation;

@Service
@Transactional
public class FirewallServiceImpl implements FirewallService {
	
	@Resource
	private FirewallDao firewallDao;

	@Override
	public boolean verify(String keyword, long minuteAfter, int count, byte type) {
		long time = System.currentTimeMillis()-minuteAfter*60*1000;
		long size = firewallDao.countCondition().start("keyword", keyword).and("time", Operation.GET, time).and("type", type).end(LockMode.PESSIMISTIC_WRITE);
		return size<count;
	}
	
	@Override
	public void add(String keyword, byte type) {
		Firewall firewall = new Firewall();
		firewall.setKeyword(keyword);
		firewall.setTime(System.currentTimeMillis());
		firewall.setType(type);
		firewallDao.save(firewall);
	}
	
	@Override
	public void clear() {
		firewallDao.deleteOverdue(7);
	}

}
